import { Response } from "got";
import moment from "moment";
import { writeFileByType } from "../../utils/util";

const processToken = (res: Response<string>) => {
  const json = JSON.parse(res.body);
  if (json.code === 1) {
    console.log(json.message);
    console.log("请重新登录");
    return ''
  } else {
    writeFileByType("iep_access_token", json.access_token);
    writeFileByType("iep_refresh_token", json.refresh_token);
    writeFileByType("iep_expires_in", json.expires_in);
    writeFileByType("iep_user_id", json.user_id);
    writeFileByType("iep_org_id", json.org_id);

    const limit_time_in = moment().add(json.expires_in, "second").unix();
    writeFileByType("iep_limit_time_in", limit_time_in);

    const d = moment.duration(json.expires_in, "seconds");
    const hours = Math.floor(d.asHours());
    const mins = Math.floor(d.asMinutes()) - hours * 60;
    const expiresStr = `${hours} 小时, ${mins} 分钟`;
    console.log(`用户 <${json.username}>(${json.user_id}) TOKEN 获取成功, TOKEN ${expiresStr} 后过期`);
    return json.access_token
  }
};
export { processToken };
